package com.example.wechat;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CacheInterceptor implements Interceptor {
    private static final int MAX_AGE = 60 * 60; // 1小时
    private static final int MAX_STALE = 60 * 60 * 24 * 7; // 7天

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        
        // 如果没有网络，使用缓存
        if (!NetworkUtils.isNetworkAvailable()) {
            request = request.newBuilder()
                    .cacheControl(new CacheControl.Builder()
                            .maxStale(MAX_STALE, java.util.concurrent.TimeUnit.SECONDS)
                            .build())
                    .build();
        }

        Response response = chain.proceed(request);

        // 有网络时，设置缓存时间
        if (NetworkUtils.isNetworkAvailable()) {
            response = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=" + MAX_AGE)
                    .build();
        }

        return response;
    }
} 